package com.liush.srb.core.controller.admin;


import com.alibaba.excel.EasyExcel;
import com.liush.srb.base.exception.SrbException;
import com.liush.srb.base.result.ResponseEnum;
import com.liush.srb.base.result.ResponseVo;
import com.liush.srb.base.util.SrbAssert;
import com.liush.srb.core.pojo.entity.Dict;
import com.liush.srb.core.pojo.vo.DictExcelVO;
import com.liush.srb.core.service.DictService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 数据字典 前端控制器
 * </p>
 *
 * @author liush
 * @since 2023-03-25
 */
@Api(tags = "数据字典模块")
//@CrossOrigin
@RestController
@RequestMapping("/admin/core/dict")
public class AdminDictController {

    @Resource
    private DictService dictService;

    @ApiOperation("根据一级数据字典dictCode查询二级数据字典集合")
    @GetMapping("list/{dictCode}")
    public ResponseVo listByDictCode(@PathVariable("dictCode") String dictCode) {
        List<Dict> dicts = dictService.getByDictCode(dictCode);
        return ResponseVo.ok().data("items", dicts);
    }

    /*
     * 处理上传的数据字典excel：解析excel数据保存到数据字典表 每一行代表一个数据字典对象
     *  1、创建javabean接收excel数据
     *  2、创建回调监听器：处理解析到的每行数据
     *  3、使用EasyExcel读取数据
     * 不能使用get方式：文件上传使用的是请求体,用post方式
     */
    @ApiOperation("导入数据字典")
    @PostMapping("import")
    public ResponseVo importDicts(@RequestParam("excel") MultipartFile file) {
        dictService.importDicts(file);
        return ResponseVo.ok().message("文件上传成功");
    }

    @ApiOperation("导出数据字典")
    @GetMapping("export")
    public void exportDicts(HttpServletResponse response) {
        try {
            //设置响应报文响应体内容的类型+编码+文件名
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("数据字典_" + new DateTime().toString("yyyy-MM-dd-HH-mm-ss"), "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            //查询数据
            List<DictExcelVO> dictExcelVos = dictService.list().stream().map(dict -> {
                DictExcelVO dictExcelVo = new DictExcelVO();
                BeanUtils.copyProperties(dict, dictExcelVo);
                return dictExcelVo;
            }).collect(Collectors.toList());
            //向response对象的输出流中写数据
            EasyExcel.write(response.getOutputStream())
                    .sheet("数据字典")
                    .head(DictExcelVO.class)
                    .doWrite(dictExcelVos);
        } catch (Exception e) {
            e.printStackTrace();
            //手动抛出异常信息
            throw new SrbException(ResponseEnum.EXPORT_DATA_ERROR);
        }
    }

    @ApiOperation("新增数据字典")
    @PostMapping
    public ResponseVo save(@RequestBody Dict dict) {
        dictService.saveChildDict(dict);
        return ResponseVo.ok().message("新增成功");
    }

    @ApiOperation("更新数据字典")
    @PutMapping
    public ResponseVo updateById(@RequestBody Dict dict) {
        dictService.updateById(dict);
        return ResponseVo.ok().message("更新成功");
    }

    @ApiOperation("根据id查询数据字典")
    @GetMapping("{id}")
    public ResponseVo getById(@PathVariable("id") Long id) {
        Dict dict = dictService.getById(id);
        return ResponseVo.ok().data("item", dict);
    }

    @ApiOperation("根据id删除数据字典")
    @DeleteMapping("{id}")
    public ResponseVo deleteById(@PathVariable("id") Long id) {
        //如果要删除的数据字典有下一级 不能删除
        SrbAssert.assertNotTrue(dictService.hasChildren(id), ResponseEnum.HAS_CHILDREN_ERROR);
        SrbAssert.assertTrue(dictService.removeById(id), ResponseEnum.ERROR);
        return ResponseVo.ok().message("删除成功");
    }

    @ApiOperation("根据父id查询数据字典和它是否有下一级数据字典的集合")
    @GetMapping("parent/{pid}")
    public ResponseVo parent(@PathVariable("pid") Long pid) {
        List<Dict> dicts = dictService.parent(pid);
        return ResponseVo.ok().data("items", dicts);
    }
}

